import socketio
from fastapi import FastAPI
from fastapi_events.handlers.local import local_handler  # 用于注册处理器
from fastapi_events.middleware import EventHandlerASGIMiddleware  # 中间件

from .core.config import setup_logging  # 导入配置
from .db.base_class import Base
from .db.session import engine
from .middlewares import LoggingMiddleware  # 导入中间件
from .routers import api  # 导入路由模块
from .socket.socketio_events import sio

# 配置日志
setup_logging()

app = FastAPI(title="Python 3.14 + FastAPI Demo", version="1.0.0")

# 配置socket
socket_app = socketio.ASGIApp(sio)


@local_handler.register(event_name="test_event")
async def test_event(event: dict):
    print("测试事件处理器", event)


# 配置事件处理器
app.add_middleware(
    EventHandlerASGIMiddleware,
    handlers=[local_handler],  # 列表中添加所有处理器函数
)

# 自动创建表
Base.metadata.create_all(bind=engine)

# 注册中间件
app.add_middleware(LoggingMiddleware)

# 挂载路由
app.include_router(api.router)
# socketio 需在路由之后挂载
app.mount("/", socket_app)
